package com.zh.common.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * Excel模板导出工具类
 *
 * @author WuZhiWei@HF
 * @since 2015-4-16
 */
@Component
public class ExcelTemplateExportUtil {
 
    static Logger log = LoggerFactory.getLogger(ExcelTemplateExportUtil.class);
 
 
 
 
    /**
     * 生成导出的Excel文件，并返回导出Excel文件的输入流
     * 生成的Excel文件是Excel 2003版本的
     *
     * @param tmpFilePath 临时文件存储路径
     * @param templateFilePath 导出模版的路径地址，例如：/WEB-INF/page/export/***.xls
     * @param dataList         要导出的数据列表
     * @param fileName         文件名称
     */
    public static void export(HttpServletRequest request, HttpServletResponse response, String tmpFilePath, String templateFilePath, List<?> dataList, String fileName) {
        Assert.hasLength(templateFilePath, "Template file path is empty while get export excel file input stream !");
        Assert.notNull(dataList, "Data list is empty while get export excel file input stream !");
 
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("dataList", dataList);
        XLSTransformer transformer = new XLSTransformer();
        try {
            String tempFilePath = tmpFilePath +"/"+ UUID.randomUUID() + ".xls";
            templateFilePath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + templateFilePath;
            transformer.transformXLS(templateFilePath, paramMap, tempFilePath);
            FileInputStream inputStream = new FileInputStream(tempFilePath);
 
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes(),"ISO8859-1"));
            OutputStream outputStream = response.getOutputStream();
            int ch;
            while ((ch = inputStream.read()) != -1) {
                outputStream.write(ch);
            }
 
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            log.error("Exception occurred while get export excel file input stream !", e);
        }
    }
 
    /**
     *
     * @param list  导出的数据
     * @param title  excel文件内容的标题
     * @param sheetName  sheet 名称
     * @param pojoClass  对应的实体类
     * @param fileName  文件名 包含后缀名
     * @param isCreateHeader
     * @param response  响应对象 用于下载
     */
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName,boolean isCreateHeader, HttpServletResponse response){
        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);
        defaultExport(list, pojoClass, fileName, response, exportParams);
 
    }
    public static void exportExcel(List<?> list, String title, String sheetName, Class<?> pojoClass,String fileName, HttpServletResponse response){
        defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName));
    }
    public static void exportExcel(List<Map<String, Object>> list, String fileName, HttpServletResponse response){
        defaultExport(list, fileName, response);
    }
 
    private static void defaultExport(List<?> list, Class<?> pojoClass, String fileName, HttpServletResponse response, ExportParams exportParams) {
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,pojoClass,list);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }
 
    /**
     *  导出操作
     * @param fileName
     * @param response
     * @param workbook
     */
    private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void defaultExport(List<Map<String, Object>> list, String fileName, HttpServletResponse response) {
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        if (workbook != null);
        downLoadExcel(fileName, response, workbook);
    }
 
    /**
     *
     * @param filePath  文件路径
     * @param titleRows  标题所占行数
     * @param headerRows  文件头所占行数
     * @param pojoClass 实体类
     * @param <T>
     * @return
     */
    public static <T> List<T> importExcel(String filePath,Integer titleRows,Integer headerRows, Class<T> pojoClass){
        if (StringUtils.isBlank(filePath)){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(new File(filePath), pojoClass, params);
        }catch (NoSuchElementException e){
           e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
    public static <T> List<T> importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass){
        if (file == null){
            return null;
        }
        ImportParams params = new ImportParams();
        params.setTitleRows(titleRows);
        params.setHeadRows(headerRows);
        List<T> list = null;
        try {
            list = ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        }catch (NoSuchElementException e){
           e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

     public static void main(String args[]) {

         //导入
        /* String filePath = "C:\\Users\\Administrator\\Desktop\\aa.xls";
         //解析excel，
         List<Test> list = importExcel(filePath,0,1,Test.class);
         //也可以使用MultipartFile,使用 FileUtil.importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class<T> pojoClass)导入
         System.out.println(Arrays.toString(list.toArray()));
         System.out.println("导入数据一共【"+list.size()+"】行");*/

         //导出
        /* List<Test> list=new ArrayList<>();
         for (int i=1;i<3;i++){
             Test test=new Test();
             test.setId(i);
             test.setName("小米"+i);
             test.setDesc("小米"+i);
             list.add(test);
         }

         ImportParams params = new ImportParams();*/

     }


}